package spring.cloud.tasks.executor.listener.task_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.listener.TreeCacheListener;
import spring.cloud.tasks.executor.listener.config.ConfigurationNode;
import spring.cloud.tasks.executor.utils.log.LogUtils;

/**
 * 作业删除
 */
@Slf4j
@Setter
@Getter
class DeleteTaskListener extends TreeCacheListener {

    private final TaskExecuteListenerHolder taskExecuteListener;

    public DeleteTaskListener(TaskExecuteListenerHolder taskExecuteListener) {
        this.taskExecuteListener = taskExecuteListener;
    }

    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (taskExecuteListener.isShutdown) {
            return;
        }
        if (ConfigurationNode.isToDeletePath(taskExecuteListener.taskId, path) && (TreeCacheEvent.Type.NODE_ADDED == treeCacheEvent.getType() || TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType())) {
            LogUtils.info(log, taskExecuteListener.taskId, "job is going to be deleted.");
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        taskExecuteListener.taskExecutor.shutdown(true);
                    } catch (Throwable t) {
                        LogUtils.error(log, taskExecuteListener.taskId, "delete job error", t);
                    }
                }
            });
            thread.setName(taskExecuteListener.executorId + "-" + taskExecuteListener.taskId + "-taskDelete");
            thread.start();
        }
    }
}
